package com.hushao.lims.weblims.service.impl;

import com.hushao.lims.weblims.domain.*;
import com.hushao.lims.weblims.repository.TeacherRepository;
import com.hushao.lims.weblims.repository.TermRepository;
import com.hushao.lims.weblims.repository.TimetableRepository;
import com.hushao.lims.weblims.service.DepartmentService;
import com.hushao.lims.weblims.service.RoleService;
import com.hushao.lims.weblims.service.TeacherService;
import com.hushao.lims.weblims.util.DateUtil;
import com.hushao.lims.weblims.util.TimetablesUtil;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 930588706
 * @date 18/1/15
 * 教师服务接口实现
 */
@Service
public class TeacherServiceImpl implements TeacherService,UserDetailsService {
    @Autowired
    private TeacherRepository teacherRepository;
    @Autowired
    private DepartmentService departmentService;
    private final String password="666666";
    @Autowired
    private RoleService roleService;
    @Autowired
    private TimetableRepository timetableRepository;

    @Autowired
    private TermRepository termRepository;
    @Autowired
    private TimetablesUtil timetablesUtil;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        TeacherInfo teacherInfo=teacherRepository.findByTeacherNumber(s);
        if(teacherInfo==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        return teacherInfo;
    }

    @Override
    public Page<TeacherInfo> listByName(String teacherName, Pageable pageable) {
        teacherName="%"+teacherName+"%";
        return teacherRepository.findByTeacherNameLike(teacherName,pageable);
    }

    @Override
    public TeacherInfo getById(Integer teacherId) {
        return teacherRepository.getOne(teacherId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String saveOrUpdate(TeacherInfo teacher, String departmentName) throws Exception {
        DepartmentInfo department=departmentService.getByName(departmentName);
        if (department==null){
            throw new Exception("你选择的院部不存在!");
        }
        String message;
        if (teacher.getTeacherId()==null){
            List<Role> roles=new ArrayList<>();
            roles.add(roleService.getById(1));
            teacher.setDepartmentInfo(department);
            teacher.setRoles(roles);
            teacher.setEncodePassword(password);
            teacherRepository.save(teacher);
            message="添加教师成功！";
        }else {
            TeacherInfo teacherNew=this.getById(teacher.getTeacherId());
            teacherNew.setTeacherNumber(teacher.getTeacherNumber());
            teacherNew.setTeacherName(teacher.getTeacherName());
            teacherNew.setDepartmentInfo(department);
            teacherNew.setTeacherPhone(teacher.getTeacherPhone());
            if(!teacher.getPassword().equals(teacherNew.getPassword())){
                teacherNew.setEncodePassword(teacher.getPassword());
            }
            teacherRepository.save(teacherNew);
            message="修改教师成功！";
        }
        return message;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void remove(Integer teacherId) throws Exception {
        teacherRepository.deleteById(teacherId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void authority(TeacherInfo teacher, Integer[] roleIds) throws Exception {
        List<Role> roles=Arrays.stream(roleIds).map(i->roleService.getById(i)).collect(Collectors.toList());
        teacher.setRoles(roles);
        teacherRepository.save(teacher);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void uploadFile(Sheet sheet) throws Exception {
        List<TeacherInfo> teachers=new LinkedList<>();
        List<Role> roles=new LinkedList<>();
        roles.add(roleService.getById(1));
        for (int i=1; i<=sheet.getLastRowNum(); i++) {
            //获取索引为i的行，以0开始
            Row row = sheet.getRow(i);
            row.getCell(0).setCellType(CellType.STRING);
            String number = row.getCell(0).getStringCellValue();
            row.getCell(1).setCellType(CellType.STRING);
            String name = row.getCell(1).getStringCellValue();
            row.getCell(2).setCellType(CellType.STRING);
            String departmentName = row.getCell(2).getStringCellValue();
            row.getCell(3).setCellType(CellType.STRING);
            String phone = row.getCell(3).getStringCellValue();

            DepartmentInfo department=departmentService.getByName(departmentName);
            if (department==null){
                throw new Exception("第"+i+"行学院错误！");
            }

            TeacherInfo teacher=new TeacherInfo(number,null,name,department,phone,roles);
            teacher.setEncodePassword(password);
            teachers.add(teacher);
        }
        teacherRepository.saveAll(teachers);
    }

    @Override
    public Map<String, Map<String, String>> timetables(TeacherInfo teacher) throws Exception {
        //根据当前时间判断学期
        String term= DateUtil.getTermByThisDate();
        //根据判断出的学期获取此学期在表中的记录
        TermInfo termInfo=termRepository.findByTerm(term);
        //根据教师，学期，获取课程记录
        List<TimetableInfo> timetables=timetableRepository.findByTeacherInfoAndTermInfo(teacher,termInfo);
        //根据 周次排序
        timetables=timetables.stream().sorted(Comparator.comparing(TimetableInfo::getCycle)).collect(Collectors.toList());
        //分组：1.根据课次(2.根据星期(3.根据试验室))  java8
        Map<String, Map<String, Map<ClassroomInfo, List<TimetableInfo>>>> map2=timetables.stream()
                .collect(Collectors.groupingBy(TimetableInfo::getLessons,
                        Collectors.groupingBy(TimetableInfo::getWeek,
                        Collectors.groupingBy(TimetableInfo::getClassroomInfo)))
                );
        //根据课次排序
        Map<String, Map<String, Map<ClassroomInfo, List<TimetableInfo>>>> sortMap = new LinkedHashMap<>();
        map2.entrySet().stream().sorted(Map.Entry.<String, Map<String, Map<ClassroomInfo, List<TimetableInfo>>>>comparingByKey())
                .forEachOrdered(x -> sortMap.put(x.getKey(), x.getValue()));
        //最终集合(将数据进行分析)并返回
        return timetablesUtil.getTimetablesByClassroom(sortMap);
    }

}
